package v1

import (
	"time"

	"github.com/gofiber/fiber/v2"
	"github.com/golang-jwt/jwt/v5"
	"github.com/spf13/cast"
)

type BaseController struct {
}

func (controller *BaseController) Auth(c *fiber.Ctx) uint64 {
	user := c.Locals("user").(*jwt.Token)
	claims := user.Claims.(jwt.MapClaims)
	return cast.ToUint64(claims["user_id"].(string))
}

func (controller *BaseController) Response(c *fiber.Ctx, status int, data interface{}) error {
	return c.Status(status).JSON(data)
}

func (controller *BaseController) Success(c *fiber.Ctx) error {
	return controller.Response(c, fiber.StatusOK, map[string]interface{}{
		"message": "success",
		"data":    map[string]interface{}{},
	})
}

func (controller *BaseController) NotFound(c *fiber.Ctx) error {
	return controller.Response(c, fiber.StatusNotFound, map[string]interface{}{
		"message": "not found",
		"data":    map[string]interface{}{},
	})
}

func (controller *BaseController) Forbidden(c *fiber.Ctx) error {
	return controller.Response(c, fiber.StatusForbidden, map[string]interface{}{
		"message": "forbidden",
		"data":    map[string]interface{}{},
	})
}

func (controller *BaseController) Faield(c *fiber.Ctx, message string) error {
	return controller.Response(c, fiber.StatusUnprocessableEntity, map[string]interface{}{
		"message": message,
		"data":    map[string]interface{}{},
	})
}

func (controller *BaseController) Json(c *fiber.Ctx, data interface{}) error {
	return controller.Response(c, fiber.StatusOK, map[string]interface{}{
		"message": "success",
		"data":    data,
	})
}

func (controller *BaseController) ValidationError(c *fiber.Ctx, errors map[string][]string) error {

	var firstErr string

	for _, err := range errors {
		firstErr = err[0]
		break
	}

	return controller.Response(c, fiber.StatusUnprocessableEntity, map[string]interface{}{
		"message": firstErr,
		"data":    map[string]string{},
	})
}

func (controller *BaseController) Unauthorized(c *fiber.Ctx, msg ...string) error {
	return controller.Response(c, fiber.StatusUnauthorized, map[string]interface{}{
		"message": defaultMessage("unauthorized request", msg...),
	})
}

func defaultMessage(defaultMsg string, msg ...string) (message string) {
	if len(msg) > 0 {
		message = msg[0]
	} else {
		message = defaultMsg
	}
	return
}

func (controller *BaseController) ToTime(strtime string) struct {
	time.Time
} {
	type FormatTime struct {
		time.Time
	}

	var Time FormatTime

	if strtime != "" {
		// 定义日期格式
		layout := "2006-01-02 15:04:05"

		// 使用 time.Parse() 函数将字符串转换为 time.Time 类型
		t, _ := time.Parse(layout, strtime)
		Time = FormatTime{
			t,
		}
	}

	return Time
}
